package org.example.mapper.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.example.entity.User;
import org.example.utils.Result;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate redisTemplate;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器");
        System.out.println(request.getRequestURI()); //打印请求路径
        if (request.getMethod().equals("OPTIONS")){ //如果是options请求，则直接放行(哨兵)
            return true;
        }

        String token=request.getHeader("token");//获取请求头中的token
        if (token==null){
            System.out.println("token:"+token);
            Result result = new Result("501", "请先登录", null);
            response.getWriter().print(JSONObject.toJSONString(result)); //返回json数据
            return false;
        }

        String json=redisTemplate.opsForValue().get(token); //根据token获取redis中的数据
        if (json==null){
            System.out.println("token:"+token);
            Result result = new Result("502", "登录过期，请重新登录", null);
            response.getWriter().print(JSONObject.toJSONString(result)); //返回json数据
            return false;
        }
        //json -> user
        User user = JSONObject.parseObject(json,User.class);  //将json字符串转换为user对象
        ThreadLocalUtil.setCurrentId((long) user.getId()); //将user对象存入ThreadLocal中

        return true;
    }
}
